package com.nulldev.util.java.scripting;

import java.util.LinkedList;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;

import com.nulldev.util.internal.JDKSupportManager;
import com.nulldev.util.internal.UnsupportedFromJDK;
import com.nulldev.util.internal.UnsupportedUntilJDK;
import com.nulldev.util.java.JVMUtil;
import com.nulldev.util.java.scripting.brainfuck.BrainfuckFactory;
import com.nulldev.util.java.scripting.nscript.jengine.nScriptEngineFactory;

/**
 * nScripting, an API for adding more ScriptEngine's to ScriptEngineManager <br>
 * Added in: 2.6.0 <br>
 * Required JDK/JRE: 1.6 or Higher.
 * @author null
 */
public class nScripting {
	
	private static final LinkedList<ScriptEngineFactory> se = new LinkedList<ScriptEngineFactory>();
	
	static {
		if (se.isEmpty()) {
			se.add(new BrainfuckFactory());
			se.add(new nScriptEngineFactory());
		}
	}
	
	private static final ScriptEngineManager se0 = (JVMUtil.getJavaVer_Double() >= 1.6 ? manager() : null);
	
	@UnsupportedUntilJDK(minSupportedJDK = 1.6)
	public static ScriptEngineManager cached() {
		JDKSupportManager.createCall();
		if (se0 == null) {
			return null;
		}
		return se0;
	}

	@UnsupportedUntilJDK(minSupportedJDK = 1.6)
	public static ScriptEngineManager manager() {
		JDKSupportManager.createCall();
		final ScriptEngineManager em = new ScriptEngineManager();
		for (final ScriptEngineFactory e : (LinkedList<ScriptEngineFactory>) se.clone()) {
			em.registerEngineName(e.getEngineName(), e);
		}
		return em;
	}
}
